import { Injectable, NgZone } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class LoadingService {

  private idPrefix = 'default-loading-';
  private showTimeoutId;

  constructor(private ngZone: NgZone) { }

  show(isPage = true, timeout = 0) {
    this.ngZone.runOutsideAngular(() => {
      if (this.showTimeoutId) {
        clearTimeout(this.showTimeoutId);
      }

      if (timeout === 0) {
        this._show(isPage);
        return;
      }

      this.showTimeoutId = setTimeout(this._show.bind(this, isPage), timeout);
    });
  }

  hide() {
    let loadingPanel = window.document.getElementById(this.idPrefix + 'page');
    loadingPanel.classList.remove('active');

    loadingPanel = window.document.getElementById(this.idPrefix + 'view');
    loadingPanel.classList.remove('active');

    this.ngZone.runOutsideAngular(() => {
      if (this.showTimeoutId) {
        clearTimeout(this.showTimeoutId);
        this.showTimeoutId = null;
      }
    });
  }

  private _show(isPage: boolean) {
    const loadingPanel = window.document.getElementById(this.idPrefix + (isPage ? 'page' : 'view'));
    loadingPanel.classList.add('active');
    this.showTimeoutId = null;
  }
}
